package com.fellansoft.moviescollection.persistence;



import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import com.fellansoft.moviescollection.R;
import com.fellansoft.moviescollection.data.CoverFlowElement;
import com.fellansoft.moviescollection.data.CoverFlowFolder;
import com.fellansoft.moviescollection.data.Movie;
import com.fellansoft.moviescollection.gui.GuiUtilities;
import com.fellansoft.moviescollection.utils.ApplicationVariables;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Codrin           ->Naty
 * Date: 5/15/12
 * Time: 4:15 PM
 * To change this template use File | Settings | File Templates.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    /**
     * The application context used to register receivers
     */
    private Context context;

    /**
     * A list of coverflow elements resulted from a database query
     */
    public static List<CoverFlowElement> result;
    /**
     * Current movie retrieved from the database
     */
    public static Movie movie;

    /**
     * The unique, private instance of this singleton
     */
    private static DatabaseHelper instance;

    /**
     * Method used to get instance of this manager
     *
     * @return Instance of DBManager
     */
    public static DatabaseHelper getInstance() {
        if (instance == null)
            instance = new DatabaseHelper();
        return instance;
    }

	public DatabaseHelper() {
		super(ApplicationVariables.getApplicationContext(), PersistenceConstants.DATABASE_NAME, null, 1);
        context = ApplicationVariables.getApplicationContext();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		//MOVIES TABLE
		db.execSQL("CREATE TABLE " + PersistenceConstants.MOVIES_TABLE + " (" + PersistenceConstants.MOVIES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PersistenceConstants.MOVIES_TITLE +
                " TEXT, " + PersistenceConstants.MOVIES_COVER + " TEXT, " + PersistenceConstants.MOVIES_FAV + " INTEGER, " + PersistenceConstants.MOVIES_WATHCLIST + " INTEGER, " +
                PersistenceConstants.MOVIES_DESCR + " TEXT, " + PersistenceConstants.MOVIES_RELEASE + " TEXT, " + PersistenceConstants.MOVIES_IMDBRATING + " REAL, " +
                PersistenceConstants.MOVIES_OWNRATING + " REAL, " + PersistenceConstants.MOVIES_DIRECTOR + " TEXT);");

		//PICTURES TABLE
		db.execSQL("CREATE TABLE " + PersistenceConstants.PICTURES_TABLE + " (" + PersistenceConstants.PICTURES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                PersistenceConstants.PICTURES_MOVIEID + " INTEGER, " + PersistenceConstants.PICTURES_PATH + " TEXT);");

		//CATEGORIES TABLE
		//db.execSQL("CREATE TABLE " + PersistenceConstants.CATEGORIES_TABLE + " (" + PersistenceConstants.CATEGORIES_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PersistenceConstants.CATEGORIES_NAME + " TEXT);");

		//MOVIE-CATEGORIES TABLE
		db.execSQL("CREATE TABLE " + PersistenceConstants.MOVIECATEGORIES_TABLE + " (" + PersistenceConstants.MOVIECATEGORIES_MOVIEID + " INTEGER, " + PersistenceConstants.MOVIECATEGORIES_CATEGORYID + " INTEGER);");

		//MORE-INFO TABLE
		db.execSQL("CREATE TABLE " + PersistenceConstants.MOREINFO_TABLE + " (" + PersistenceConstants.MOREINFO_MOVIEID + " INTEGER, " + PersistenceConstants.MOREINFO_RUNTIME + " INTEGER, " +
                PersistenceConstants.MOREINFO_DESCRIPTION + " TEXT);");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		android.util.Log.w("Constants", "Upgrading database, which will destroy all old data");
		// db.execSQL("DROP TABLE IF EXISTS constants");
		onCreate(db);
	}

    /*
    public void openDatabase() {
        SQLiteDatabase.openDatabase(PersistenceConstants.DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);
    }
    */

    private void insertPictures(SQLiteDatabase db, Movie m, Long id) {

        ContentValues cv = new ContentValues();

        // Add informations in PICTURES TABLE
            for(Uri path : m.getPhotos()) {
                cv.clear();
                cv.put(PersistenceConstants.PICTURES_MOVIEID, id);
                cv.put(PersistenceConstants.PICTURES_PATH, path.toString());
                db.insert(PersistenceConstants.PICTURES_TABLE, null, cv);
            }
    }

    private void insertCategories(SQLiteDatabase db, Movie m, Long id) {

        ContentValues cv = new ContentValues();

        // Add informations in MOVIE-CATEGORIES TABLE
            for(int i = 0; i < m.getCategories().length; i++) {
                cv.clear();
                if(m.getCategories()[i]) {
                    cv.put(PersistenceConstants.MOVIECATEGORIES_MOVIEID, id);
                    cv.put(PersistenceConstants.MOVIECATEGORIES_CATEGORYID, i);
                    db.insert(PersistenceConstants.MOVIECATEGORIES_TABLE, null, cv);
                }
            }
    }

    private ContentValues assignContentValues(Movie m) {

        ContentValues cv = new ContentValues();

        cv.put(PersistenceConstants.MOVIES_TITLE, m.getTitle());
        cv.put(PersistenceConstants.MOVIES_COVER, m.getCoverPhoto().toString());
        cv.put(PersistenceConstants.MOVIES_FAV, m.getFavorite());
        cv.put(PersistenceConstants.MOVIES_WATHCLIST, m.getWatchList());
        cv.put(PersistenceConstants.MOVIES_DESCR, m.getDescription());
        if (m.getReleaseDate() != null)
            cv.put(PersistenceConstants.MOVIES_RELEASE, m.getReleaseDate().getTime()/1000);
        //cv.put(PersistenceConstants.MOVIES_IMDBRATING, m.getImdbRating());
        cv.put(PersistenceConstants.MOVIES_OWNRATING, m.getOwnRating());
        //cv.put(PersistenceConstants.MOVIES_DIRECTOR, m.getDirector());

        return  cv;
    }

    public void saveMovie(Movie m) {

        SQLiteDatabase db = this.getReadableDatabase();

        // insert new MOVIE
        ContentValues cv = assignContentValues(m);
        Long id = db.insert(PersistenceConstants.MOVIES_TABLE, null, cv);

        if(id < 0)
            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_SAVE_ERROR));

        else {

            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_SAVED_SUCCESSFULLY));

            this.insertCategories(db, m, id);
            this.insertPictures(db, m, id);
            /**
             * Add informations in MORE-INFO TABLE - IMDB SH*T
             * -----------------------------------
             * cv.clear();
             * cv.put(PersistenceConstants.MOREINFO_MOVIEID, id);
             * cv.put(PersistenceConstants.MOREINFO_RUNTIME, );
             * cv.put(PersistenceConstants.MOREINFO_DESCRIPTION, );
             * db.insert(PersistenceConstants.MOREINFO_TABLE, null, cv);
             */
        }
        db.close();
    }

    public void updateMovie(Movie m) {

        SQLiteDatabase db = this.getReadableDatabase();

        // delete old pictures and categories
        db.delete(PersistenceConstants.MOVIECATEGORIES_TABLE, PersistenceConstants.MOVIECATEGORIES_MOVIEID + "=?", new String[]{String.valueOf(m.getId())});
        db.delete(PersistenceConstants.PICTURES_TABLE, PersistenceConstants.PICTURES_MOVIEID + "=?", new String[]{String.valueOf(m.getId())});

        // update the movie
        ContentValues cv = assignContentValues(m);

        int result = db.update(PersistenceConstants.MOVIES_TABLE, cv, PersistenceConstants.MOVIES_ID + "=?", new String []{String.valueOf(m.getId())});

        if(result != 1)
            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIES_UPDATED_ERROR));
        else
            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIES_UPDATED_SUCCESSFULLY));

        // insert the new pictures and categories
        this.insertCategories(db, m, m.getId());
        this.insertPictures(db, m, m.getId());

        db.close();
    }

    public void deleteMovie(Long id) {

        SQLiteDatabase db = this.getReadableDatabase();

        // delete old pictures and categories
        db.delete(PersistenceConstants.MOVIECATEGORIES_TABLE, PersistenceConstants.MOVIECATEGORIES_MOVIEID + "=?", new String [] {String.valueOf(id)});
        db.delete(PersistenceConstants.PICTURES_TABLE, PersistenceConstants.PICTURES_MOVIEID + "=?", new String [] {String.valueOf(id)});

        // delete the old movie
        int result = db.delete(PersistenceConstants.MOVIES_TABLE, PersistenceConstants.MOVIES_ID + "=?", new String[]{String.valueOf(id)});

        if(result != 1)
            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_DELETED_ERROR));
        else
            context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_DELETED_SUCCESSFULLY));

        db.close();
    }

    public void searchMovies(String s)
    {
        final String ss = s;
        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                SQLiteDatabase db = getReadableDatabase();

                result = new ArrayList<CoverFlowElement>();
                Cursor cursor = null;

                cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[]
                        {PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                        PersistenceConstants.MOVIES_TITLE+" LIKE '%"+ss+"%'",null,null,null,PersistenceConstants.MOVIES_TITLE);

                while(cursor.moveToNext()) {

                        Bitmap cover = null;
                        try {
                            cover = GuiUtilities.getThumbnailFromUri(Uri.parse(cursor.getString(0)), 4 * ApplicationVariables.getDisplayHeight() / 15);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }

                        result.add(new CoverFlowElement(cover, Integer.valueOf(cursor.getString(1)), cursor.getString(2)));
                    }

                cursor.close();

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIES_FROM_SEARCH_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMovieById(Long id) {
        final Long idd=id;
        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                SQLiteDatabase db = getReadableDatabase();
                String[] columns={
                        PersistenceConstants.MOVIES_TITLE,PersistenceConstants.MOVIES_RELEASE,PersistenceConstants.MOVIES_DESCR,PersistenceConstants.MOVIES_FAV,
                        PersistenceConstants.MOVIES_OWNRATING,PersistenceConstants.MOVIES_WATHCLIST,PersistenceConstants.MOVIES_COVER} ;
               // String[] param={Long.toString(idd)};

                Cursor cursor=db.query(PersistenceConstants.MOVIES_TABLE,columns,PersistenceConstants.MOVIES_ID+"="+idd,null,null,null,null);


                //   Cursor cursor=db.rawQuery()
                if (cursor == null)
                    context.sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_GETBYID_ERROR));

                cursor.moveToFirst();

                //public Movie(Long id00, String title 0, Date releaseDate 1, String description 2, boolean[] categories 33, Boolean watchList3, Boolean favorite4, Float ownRating5, Float imdbRating6, Uri coverPhoto, List<Uri> photos)
                 movie=new Movie(idd ,cursor.getString(cursor.getColumnIndex(PersistenceConstants.MOVIES_TITLE)),null,cursor.getString(cursor.getColumnIndex(PersistenceConstants.MOVIES_DESCR))
                        ,null,cursor.getInt(cursor.getColumnIndex(PersistenceConstants.MOVIES_WATHCLIST))==1
                         ,cursor.getInt(cursor.getColumnIndex(PersistenceConstants.MOVIES_FAV))==1, cursor.getFloat(cursor.getColumnIndex(PersistenceConstants.MOVIES_OWNRATING)),
                        null,Uri.parse(cursor.getString(cursor.getColumnIndex(PersistenceConstants.MOVIES_COVER))),null);

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(PersistenceConstants.MOVIES_RELEASE))*1000);

                movie.setReleaseDate(calendar.getTime());

                cursor.close();

                movie.setCategories(getCategories(idd,db));
                movie.setPhotos(getUriList(idd,db));
                //still needs date,categories,uriList
                Log.d("RET", movie.getTitle())   ;

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIE_GETBYID_SUCCESSFULLY);

                //Attach the list to the intent
           //     resultIntent.putExtra(PersistenceConstants.PC_MOVIE_GETBYID_SUCCESSFULLY,movie);

                //Broadcast intent
                context.sendBroadcast(resultIntent);
                db.close();

            }
        }) ;
        backgroundThread.start();
    }

    public void getMoviesAlphabetically()
    {
        final SQLiteDatabase db = this.getReadableDatabase();

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();

                List<Uri> uris = new ArrayList<Uri>(4);
                Cursor cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER},
                        "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))<? OR upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))>?", new String[] {"A","Z"},
                        null,null, PersistenceConstants.MOVIES_TITLE , "4");

                while(cursor.moveToNext())
                {
                    uris.add(Uri.parse(cursor.getString(0)));
                }
                cursor.close();
                CoverFlowElement elem = null;
                if (uris.size() > 0)
                {
                    for (int i=uris.size(); i<4;i++)
                        uris.add(null);
                    try {
                        elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                        elem.setLabel("123");
                        result.add(elem);
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }


                for (char lit='A'; lit <= 'Z'; lit++)
                {
                    uris = new ArrayList<Uri>(4);
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))=?", new String[] {String.valueOf(lit)}, null,
                            null, PersistenceConstants.MOVIES_TITLE , "4");
                    while(cursor.moveToNext())
                    {
                        if (cursor.getString(0) != null)
                            uris.add(Uri.parse(cursor.getString(0)));
                    }
                    cursor.close();
                    if (uris.size() > 0)
                    {
                        for (int i=uris.size(); i<4;i++)
                            uris.add(null);
                        try {
                            elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                            elem.setLabel(String.valueOf(lit));
                            result.add(elem);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                    }

                }

                Intent resultIntent = new Intent(PersistenceConstants.PC_FOLDERS_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesByCollections()
    {
        final SQLiteDatabase db = this.getReadableDatabase();

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();

               /* List<Uri> uris = new ArrayList<Uri>(4);
                Cursor cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER},
                        "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))<=? AND upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))>=?", new String[] {"A","Z"},
                        null,null, PersistenceConstants.MOVIES_TITLE , "4");

                while(cursor.moveToNext())
                {
                    uris.add(Uri.parse(cursor.getString(0)));
                }
                cursor.close();

                for (int i=uris.size(); i<4;i++)
                    uris.add(null);
                CoverFlowElement elem = null;
                try {
                    elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                    elem.setLabel("123");
                    result.add(elem);
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }


                for (char lit='A'; lit <= 'Z'; lit++)
                {
                    uris = new ArrayList<Uri>(4);
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))=?", new String[] {String.valueOf(lit)}, null,
                            null, PersistenceConstants.MOVIES_TITLE , "4");
                    while(cursor.moveToNext())
                    {
                        if (cursor.getString(0) != null)
                            uris.add(Uri.parse(cursor.getString(0)));
                    }
                    cursor.close();
                    for (int i=uris.size(); i<4;i++)
                        uris.add(null);
                    try {
                        elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                        elem.setLabel(String.valueOf(lit));
                        result.add(elem);
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }

                }        */

                Intent resultIntent = new Intent(PersistenceConstants.PC_FOLDERS_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesForALetter(String letter)
    {
        final SQLiteDatabase db = this.getReadableDatabase();
        final String letterFinal = letter;

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();
                Cursor cursor = null;

                if(letterFinal.equals("123"))
                {
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))<=? OR upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))>=?", new String[] {"A","Z"},
                            null,null, PersistenceConstants.MOVIES_TITLE );
                }

                else
                {
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))=?", new String[] {String.valueOf(letterFinal)}, null,
                            null, PersistenceConstants.MOVIES_TITLE);
                }

                while(cursor.moveToNext()) {

                        Bitmap cover = null;
                        try {
                            cover = GuiUtilities.getThumbnailFromUri(Uri.parse(cursor.getString(0)), 4 * ApplicationVariables.getDisplayHeight() / 15);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }

                        result.add(new CoverFlowElement(cover, Integer.valueOf(cursor.getString(1)), cursor.getString(2)));
                    }

                cursor.close();

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIES_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesForACollection(int collection)
    {
        final SQLiteDatabase db = this.getReadableDatabase();
        final int collectionFinal = collection;

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();
                Cursor cursor = null;

               /* if(letterFinal.equals("123"))
                {
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))<=? AND upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))>=?", new String[] {"A","Z"},
                            null,null, PersistenceConstants.MOVIES_TITLE );
                }

                else
                {
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE,new String[] {PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                            "upper(substr(" + PersistenceConstants.MOVIES_TITLE + ",1,1))=?", new String[] {String.valueOf(letterFinal)}, null,
                            null, PersistenceConstants.MOVIES_TITLE);
                }

                while(cursor.moveToNext()) {

                        Bitmap cover = null;
                        try {
                            cover = GuiUtilities.getThumbnailFromUri(Uri.parse(cursor.getString(0)), 4 * ApplicationVariables.getDisplayHeight() / 15);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }

                        result.add(new CoverFlowElement(cover, Integer.valueOf(cursor.getString(1)), cursor.getString(2)));
                    }

                cursor.close(); */

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIES_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesGenre()
    {
        final SQLiteDatabase db = this.getReadableDatabase();

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                result = new ArrayList<CoverFlowElement>();
                CharSequence[] categories = ApplicationVariables.getApplicationContext().getResources().getStringArray(R.array.Categories);
                List<Uri> uris = null;
                Cursor cursor = null;
                CoverFlowElement elem = null;
                for (int i=0; i < categories.length; i++)
                {
                    uris = new ArrayList<Uri>(4);
                    cursor = db.rawQuery("select " + PersistenceConstants.MOVIES_COVER + " from " + PersistenceConstants.MOVIES_TABLE
                            + " inner join (select " + PersistenceConstants.MOVIECATEGORIES_MOVIEID
                            + " from " + PersistenceConstants.MOVIECATEGORIES_TABLE
                            + " where " + PersistenceConstants.MOVIECATEGORIES_CATEGORYID + "=? limit 4) as mm "
                            + " ON " + PersistenceConstants.MOVIES_TABLE + "." + PersistenceConstants.MOVIES_ID + "=mm." + PersistenceConstants.MOVIECATEGORIES_MOVIEID,
                            new String[] {String.valueOf(i)});

                    while(cursor.moveToNext())
                    {
                        if (cursor.getString(0) != null)
                            uris.add(Uri.parse(cursor.getString(0)));
                    }
                    cursor.close();

                    if (uris.size() > 0)
                    {
                        for (int j=uris.size(); j<4;j++)
                            uris.add(null);
                        try {
                            elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                            elem.setLabel(categories[i].toString());
                            elem.setId(i);
                            result.add(elem);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                    }

                }
                Intent resultIntent = new Intent(PersistenceConstants.PC_FOLDERS_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesForAGenre(int genre)
    {
        final SQLiteDatabase db = this.getReadableDatabase();
        final int genreFinal = genre;

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();
                Cursor cursor = null;

                cursor = db.rawQuery("select " + PersistenceConstants.MOVIES_COVER + " , " +  PersistenceConstants.MOVIES_ID + " , " +  PersistenceConstants.MOVIES_TITLE + " from " + PersistenceConstants.MOVIES_TABLE
                            + " inner join (select " + PersistenceConstants.MOVIECATEGORIES_MOVIEID
                            + " from " + PersistenceConstants.MOVIECATEGORIES_TABLE
                            + " where " + PersistenceConstants.MOVIECATEGORIES_CATEGORYID + "=? ) as mm "
                            + " ON " + PersistenceConstants.MOVIES_TABLE + "." + PersistenceConstants.MOVIES_ID + "=mm." + PersistenceConstants.MOVIECATEGORIES_MOVIEID,
                            new String[] {String.valueOf(genreFinal)});

                while(cursor.moveToNext()) {

                        Bitmap cover = null;
                        try {
                            cover = GuiUtilities.getThumbnailFromUri(Uri.parse(cursor.getString(0)), 4 * ApplicationVariables.getDisplayHeight() / 15);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }

                        result.add(new CoverFlowElement(cover, Integer.valueOf(cursor.getString(1)), cursor.getString(2)));
                    }

                cursor.close();

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIES_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesByReleaseYear()
    {
        final SQLiteDatabase db = this.getReadableDatabase();

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {
                result = new ArrayList<CoverFlowElement>();
                List<Uri> uris = null;
                Cursor cursor = null;
                CoverFlowElement elem = null;
                List<Integer> years = new ArrayList<Integer>();
                cursor = db.query(true, PersistenceConstants.MOVIES_TABLE,
                        new String[] {"strftime('%Y',datetime(" + PersistenceConstants.MOVIES_RELEASE + ", 'unixepoch')) as data"},
                       null, null, null, null, "data", null);
                while(cursor.moveToNext())
                {
                    if (cursor.getString(0) != null && cursor.getString(0).length() > 0)
                    years.add(cursor.getInt(0));
                }
                cursor.close();

                for (int i=0; i < years.size(); i++)
                {
                    uris = new ArrayList<Uri>(4);
                    cursor = db.query(PersistenceConstants.MOVIES_TABLE, new String[]{PersistenceConstants.MOVIES_COVER},
                            "strftime('%Y',datetime(" + PersistenceConstants.MOVIES_RELEASE + ", 'unixepoch'))=?",
                            new String[]{String.valueOf(years.get(i))},null,null,null,"4");

                    while(cursor.moveToNext())
                    {
                        if (cursor.getString(0) != null)
                            uris.add(Uri.parse(cursor.getString(0)));
                    }

                    cursor.close();

                    for (int j=uris.size(); j<4;j++)
                        uris.add(null);

                    try {
                        elem = new CoverFlowFolder(ApplicationVariables.getApplicationContext(),uris.get(0),uris.get(1),uris.get(2),uris.get(3));
                        elem.setLabel(String.valueOf(years.get(i)));
                        result.add(elem);
                    } catch (IOException e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }

                Intent resultIntent = new Intent(PersistenceConstants.PC_FOLDERS_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }

    public void getMoviesForAYear(int year)
    {
        final SQLiteDatabase db = this.getReadableDatabase();
        final int yearFinal = year;

        Thread backgroundThread = new Thread(new Runnable() {
            public void run() {

                result = new ArrayList<CoverFlowElement>();
                Cursor cursor = null;

                cursor = db.query(PersistenceConstants.MOVIES_TABLE, new String[]{PersistenceConstants.MOVIES_COVER, PersistenceConstants.MOVIES_ID, PersistenceConstants.MOVIES_TITLE},
                            "strftime('%Y',datetime(" + PersistenceConstants.MOVIES_RELEASE + ", 'unixepoch'))=?",
                            new String[]{String.valueOf(yearFinal)},null,null,null);

                while(cursor.moveToNext()) {

                        Bitmap cover = null;
                        try {
                            cover = GuiUtilities.getThumbnailFromUri(Uri.parse(cursor.getString(0)), 4 * ApplicationVariables.getDisplayHeight() / 15);
                        } catch (IOException e) {
                            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }

                        result.add(new CoverFlowElement(cover, Integer.valueOf(cursor.getString(1)), cursor.getString(2)));
                    }

                cursor.close();

                Intent resultIntent = new Intent(PersistenceConstants.PC_MOVIES_RECEIVED_SUCCESSFULLY);
                context.sendBroadcast(resultIntent);
            }
        });
        backgroundThread.start();
    }


    public Movie getMovie()
    {
        return this.movie;
    }
    public List<Uri> getUriList(Long id, SQLiteDatabase db)
    {
        final Long idd=id;
        final List<Uri> listUri=new ArrayList<Uri>();


        String[] columns={
                PersistenceConstants.PICTURES_MOVIEID,PersistenceConstants.PICTURES_PATH} ;
        // String[] param={Long.toString(idd)};

        Cursor cursor=db.query(PersistenceConstants.PICTURES_TABLE,columns,PersistenceConstants.PICTURES_MOVIEID+"="+idd,null,null,null,null);
        while(cursor.moveToNext())
        {
          //  Log.d("CATEG",Integer.toString(cursor.getInt(cursor.getColumnIndex(PersistenceConstants.MOVIECATEGORIES_CATEGORYID))));
            listUri.add(Uri.parse(cursor.getString(cursor.getColumnIndex(PersistenceConstants.PICTURES_PATH))));
        }
        cursor.close();

        //  Resources res =ApplicationVariables.getApplicationContext().getResources();
        return listUri;
    }
    public boolean[] getCategories(Long id,SQLiteDatabase db)
    {
        final Long idd=id;
       final List<Integer> listCateg=new ArrayList<Integer>();


                String[] columns={
                        PersistenceConstants.MOVIECATEGORIES_CATEGORYID,PersistenceConstants.MOVIECATEGORIES_MOVIEID} ;
                // String[] param={Long.toString(idd)};

                Cursor cursor=db.query(PersistenceConstants.MOVIECATEGORIES_TABLE,columns,PersistenceConstants.MOVIECATEGORIES_MOVIEID+"="+idd,null,null,null,null);
                while(cursor.moveToNext())
                {
                        Log.d("CATEG",Integer.toString(cursor.getInt(cursor.getColumnIndex(PersistenceConstants.MOVIECATEGORIES_CATEGORYID))));
                       listCateg.add(cursor.getInt(cursor.getColumnIndex(PersistenceConstants.MOVIECATEGORIES_CATEGORYID)));
                }
                cursor.close();

     //  Resources res =ApplicationVariables.getApplicationContext().getResources();
                  int len=26;

        boolean [] arrayBool=new boolean[26];

        for(int i=0; i<len; i++)
        {
            if(listCateg.contains(i)==true)
            {
               arrayBool[i]=true;
            }
            else
               arrayBool[i]=false;
        }
        return arrayBool;
    }


}